package com.hsfw.pmauthzuul.filter;

import com.google.gson.Gson;
import com.hsfw.dbmodule.utils.BaseResponse;
import com.hsfw.dbmodule.utils.ResponseCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by RAZR on 16:14 2019/3/22.
 */
@Component("RestAuthenticationAccessDeniedHandler")
public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        Gson gson=new Gson();
        //登陆状态下，权限不足执行该方法
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        String body = gson.toJson(BaseResponse.buildResponse().setCode(ResponseCode.UNAUTHORIZED).setMessage(e.getMessage()).build());
        printWriter.write(body);
        printWriter.flush();
    }
}
